package service

import (
	"ruoyi-go/app/admin/model/constants"
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/cache/redisCache"
)

var SysConfigCacheService = &sysConfigCacheService{}

type sysConfigCacheService struct{}

// InitSysConfigCache 初始化参数配置到redis
func (service sysConfigCacheService) InitSysConfigCache() {
	var param = tools.SearchTableDataParam{
		Other: system.SysConfig{},
	}
	result := SysConfigService.SelectConfigList(param, false)
	list := result.Rows.([]system.SysConfig)
	for _, config := range list {
		service.SetSysConfigCache(config.ConfigKey, config.ConfigValue)
	}
}

// RefreshSysConfigCache 刷新某个参数配置的所有值
func (service sysConfigCacheService) RefreshSysConfigCache(configKey string) {
	config := SysConfigService.SelectConfigByKey(configKey)
	service.SetSysConfigCache(configKey, config)
}

// GetSysConfigCacheByKey 根据参数配置来获取字典数据
func (service sysConfigCacheService) GetSysConfigCacheByKey(configKey string) string {
	get, err := redisCache.RedisDB.Get(constants.SysConfigCacheKey + configKey)
	if err != nil {
		return ""
	}
	return get
}

// SetSysConfigCache 设置参数配置 值
func (service sysConfigCacheService) SetSysConfigCache(configKey string, configValue string) {
	redisCache.RedisDB.Put(constants.SysConfigCacheKey+configKey, configValue, 0)
}

// DeleteSysConfigCache 删除字典
func (service sysConfigCacheService) DeleteSysConfigCache(configKey string) {
	redisCache.RedisDB.Del(constants.SysConfigCacheKey + configKey)
}

func (service sysConfigCacheService) DeleteAllSysConfigCache() error {
	keys, _, err := redisCache.RedisDB.Scan(0, constants.SysConfigCacheKey+"*", constants.ScanCountMax)
	if err != nil {
		return err
	}
	for _, key := range keys {
		redisCache.RedisDB.Del(key)
	}
	return nil
}
